package com.example.myapplication.ui.download

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Rect
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.R
import com.example.myapplication.common.AbstractFragment
import com.example.myapplication.extensions.beGone
import com.example.myapplication.extensions.beVisible
import com.example.myapplication.extensions.runOnUIThread
import com.example.myapplication.extensions.toast
import com.example.myapplication.test.MyDecoration
import com.example.myapplication.test.SimpleItemDecoration
import com.example.myapplication.ui.FileBean
import com.example.myapplication.ui.download.FileDownloadBean.Companion.DOWNLOAD_FINISH
import com.example.myapplication.ui.download.FileDownloadBean.Companion.DOWNLOAD_READY
import com.example.myapplication.ui.download.FileDownloadBean.Companion.DOWNLOAD_RUNNING
import com.example.myapplication.ui.upload.FileUploadBean
import com.example.myapplication.utils.DiffUIDataUtil
import com.example.myapplication.utils.OpenUtil
import com.example.myapplication.view.SideSlipLayout
import com.example.myapplication.view.SimpleRecyclerAdapter
import com.saop.annotation.AopLog
import java.io.File


class FileDownloadFragment : AbstractFragment() {

    private val viewModel: FileDownloadViewModel by lazy {
        ViewModelProvider(
            requireActivity()
        ).get(FileDownloadViewModel::class.java)
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_file_download
    }

    private val adapter = object : SimpleRecyclerAdapter<FileDownloadBean>() {
        override fun getItemViewType(position: Int, data: FileDownloadBean): Int {
            if (data.type == 0) {
                return R.layout.item_title_file
            }
            return R.layout.item_download_file
        }

        override fun onCreateViewHolder(
            contentView: View,
            viewType: Int
        ): SimpleViewHolder<FileDownloadBean> {
            if (viewType == R.layout.item_title_file) {
                return TitleViewHolder(contentView)
            }
            return ViewHolder(contentView)
        }

        override fun updateView(view: View) {
            super.updateView(view)
            val parent = view.parent
            if (parent is RecyclerView) {
                parent.children.forEach {
                    if (it != view && it is SideSlipLayout) {
                        it.setOpenByAnimation(false)
                    }
                }
            }
        }
    }


    override fun initView(contentView: View) {
        super.initView(contentView)
        contentView.findViewById<RecyclerView>(R.id.rv_file_download).also {
            it.itemAnimator = null
            it.adapter = adapter
            it.setHasFixedSize(true)
            it.addItemDecoration(MyDecoration().apply {
                this.setMargin(50f)
            })
            it.layoutManager = LinearLayoutManager(contentView.context)
            it.addOnChildAttachStateChangeListener(adapter.childStateChangeListener)
        }
    }

    override fun onFirstInit() {
        super.onFirstInit()
        viewModel.updateAllTaskState()
    }

    override fun initData() {
        super.initData()
        this.lifecycle.addObserver(viewModel)
        viewModel.getAllFileByFlow().observe(this, { words ->
            requireContext().runOnUIThread {
                val callback = DiffUIDataUtil(adapter.getItems(), words)
                val result = DiffUtil.calculateDiff(callback)
                adapter.getItems().clear()
                adapter.getItems().addAll(words)
                result.dispatchUpdatesTo(adapter)
            }
        })
    }

    inner class ViewHolder(itemView: View) :
        SimpleRecyclerAdapter.SimpleViewHolder<FileDownloadBean>(itemView) {

        private val name: TextView
        private val downloadState: TextView
        private val speed: TextView
        private val retry: View
        private val icon: ImageView

        init {
            name = itemView.findViewById(R.id.name)
            downloadState = itemView.findViewById(R.id.state)
            speed = itemView.findViewById(R.id.speed)
            itemView.findViewById<View>(R.id.retry).also {
                this.retry = it
            }.setOnClickListener { retryBean() }
            icon = itemView.findViewById(R.id.icon)
            itemView.findViewById<View>(R.id.tv_delete).setOnClickListener {
                deleteBean()
            }
            itemView.findViewById<View>(R.id.tag_sild_slip_layout_left_view).setOnClickListener {
                // 打开文件
                openBean()
            }
            itemView.findViewById<SideSlipLayout>(R.id.side_silp_layout).sildListener =
                object : SideSlipLayout.SideSlipListener {
                    override fun onMenuState(isShow: Boolean, contentView: View) {
                        if (isShow) {
                            callback?.updateView(itemView)
                        }
                    }
                }
        }

        @SuppressLint("SetTextI18n")
        override fun onBindView(newData: FileDownloadBean, oldData: FileDownloadBean?) {
            equalToUpdataUI(newData.path, oldData?.path) {
                try {
                    val path = newData.path ?: throw Exception("path is null")
                    val file = File(path)
                    if (!file.exists()) throw Exception("file is not exists")
                    val type = file.extension
                    when (type.lowercase()) {
                        "pdf" -> icon.setBackgroundResource(R.mipmap.pdf_icon)
                        "jpg", "png" -> icon.setBackgroundResource(R.mipmap.image_icon)
                        "doc", "docx" -> icon.setBackgroundResource(R.mipmap.word_icon)
                        "xls", "xlsx" -> icon.setBackgroundResource(R.mipmap.excel_icon)
                        "vsd", "vsdx" -> icon.setBackgroundResource(R.mipmap.v_icon)
                        "ppt", "pptx" -> icon.setBackgroundResource(R.mipmap.ppt_icon)
                        else -> icon.setBackgroundResource(R.mipmap.not_supper_icon)
                    }
                } catch (e: Exception) {
                    icon.setBackgroundResource(R.mipmap.image_nfind_icon)
                }
            }

            equalToUpdataUI(newData.name, oldData?.name) {
                name.text = it
            }

            equalToUpdataUI(newData.state, oldData?.state) {
                val value: String
                if (it.startsWith(FileBean.STATE_NET_FLAG)) {
                    downloadState.setTextColor(Color.RED)
                    value = it.substringAfter(FileBean.STATE_NET_FLAG)
                } else if (it.startsWith(FileBean.STATE_LOCAL_FLAG)) {
                    downloadState.setTextColor(Color.RED)
                    value = it.substringAfter(FileBean.STATE_LOCAL_FLAG)
                } else {
                    downloadState.setTextColor(Color.BLACK)
                    value = it.substringAfter(FileBean.STATE_DEFAULT_FLAG)
                }
                downloadState.text = value
            }

            equalToUpdataUI(newData.downloadSpeed, oldData?.downloadSpeed) {
                speed.text = "${it}KB/S"
            }

            if (newData.downloadState != FileUploadBean.UPLOAD_ERROR) {
                retry.beGone()
            } else {
                retry.beVisible()
            }

            if (retry.isVisible) {
                speed.beGone()
            } else {
                if (newData.downloadState == DOWNLOAD_READY || newData.downloadState == DOWNLOAD_FINISH) {
                    speed.beGone()
                } else {
                    speed.beVisible()
                }
            }
        }

        private fun deleteBean() {
            mData?.also {
                if (itemView is SideSlipLayout) {
                    itemView.setOpen(false)
                }
                viewModel.deleteByUUID(it)
            }
        }

        private fun retryBean() {
            mData?.also {
                viewModel.retry(it)
            }
        }

        private fun openBean() {
            try {
                val path = mData?.path ?: throw Exception("path is null")
                val intent = OpenUtil.openFileByIntent(requireActivity(), path)
                    ?: throw Exception("Intent is null")
                requireActivity().startActivity(intent)
            } catch (e: Exception) {
                requireActivity().toast("打开失败，请重试")
            }
        }
    }

    inner class TitleViewHolder(itemView: View) :
        SimpleRecyclerAdapter.SimpleViewHolder<FileDownloadBean>(itemView) {

        private val name: TextView
        private val active: TextView

        init {
            name = itemView.findViewById(R.id.title)
            active = itemView.findViewById(R.id.active)
        }

        override fun onBindView(newData: FileDownloadBean, oldData: FileDownloadBean?) {
            equalToUpdataUI(newData.name, oldData?.name) {
                name.text = it
            }
            equalToUpdataUI(newData.downloadState, oldData?.downloadState) {
                if (it == DOWNLOAD_FINISH) {
                    active.setText("全部删除")
                    active.setOnClickListener {
                        viewModel.deleteAll()
                    }
                }
            }
        }
    }


    private fun createFile(init: File): File {
        if (init.exists()) {
            return createFile(
                File(
                    init.parentFile,
                    "${init.nameWithoutExtension}_1.${init.extension}"
                )
            )
        }
        return init
    }

    private fun createTile() {
        viewModel.insert(FileDownloadBean().apply {
            this.name = "进行中"
            this.type = 0
            this.url = null
            this.downloadState = DOWNLOAD_RUNNING
            this.enabled = false
        })
        viewModel.insert(FileDownloadBean().apply {
            this.name = "已完成"
            this.type = 0
            this.url = null
            this.downloadState = DOWNLOAD_FINISH
            this.enabled = false
        })
    }

    @AopLog(priority = Log.ERROR, tag = "FileDownloadFragment")
    override fun onMoreItemSelected(value: String): Boolean {
        when (value) {
            "打开" -> {
                val edit = EditText(requireContext())
                edit.setText("https://www.apple.com/105/media/cn/iphone-x/2017/01df5b43-28e4-4848-bf20-490c34a926a7/films/feature/iphone-x-feature-cn-20170912_1280x720h.mp4")
                AlertDialog.Builder(requireContext())
                    .setTitle("输入下载路径")
                    .setIcon(android.R.drawable.btn_star)
                    .setView(edit)
                    .setPositiveButton(
                        "确认"
                    ) { dialog, which ->
                        val bean = FileDownloadBean().apply {
                            this.length = 0
                            this.downloadSize = 0
                            this.downloadState = DOWNLOAD_READY
                            val url = edit.text.toString()
                            this.url = url
                            val index: Int = url.lastIndexOf(File.separatorChar)
                            val file = createFile(
                                File(
                                    requireContext().externalCacheDir,
                                    url.substring(index + 1)
                                )
                            )
                            this.path = file.absolutePath
                            this.name = file.name
                            this.state = "${FileBean.STATE_DEFAULT_FLAG}正在等待..."
                        }
                        viewModel.insert(bean)
                    }
                    .setNegativeButton("取消") { dialog, which ->
                        dialog.dismiss()
                    }.show()
            }
            "预设" -> {
                createTile()
                //viewModel.updateTest()
            }
            "清空进行" -> {
                viewModel.deleteRunningTask()
            }
            "刷新失败" -> {
                viewModel.updateErrorTask()
            }
            "清空失败" -> {
                viewModel.deleteErrorTask()
            }
        }
        return super.onMoreItemSelected(value)
    }

}